package io.sk.common;

import io.sk.common.base.Constants;
import io.sk.common.utils.ContextHolderUtil;
import io.sk.common.utils.DateConvertEditor;
import io.sk.entity.SysUserEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 基础controller
 *
 * @author King
 */
public class BaseController extends io.sk.common.base.BaseController {

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     *
     * @param binder 日期
     */
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateConvertEditor());
    }

    /**
     * 抽取由逗号分隔的主键列表
     *
     * @param ids 主键集
     * @return List<String>
     */
    protected List<String> extractIdListByComma(String ids) {
        List<String> result = new ArrayList<String>();
        if (StringUtils.hasText(ids)) {
            for (String id : ids.split(Constants.STRING_DELIMITER_COMMA)) {
                if (StringUtils.hasLength(id)) {
                    result.add(id.trim());
                }
            }
        }

        return result;
    }

    /**
     * 设置session信息
     *
     * @param key   键
     * @param value 值
     */
    public void setSession(String key, Object value) {

        HttpSession session = ContextHolderUtil.getSession();
        session.setAttribute(key, value);
    }

    /**
     * 获取登录的当前用户信息
     *
     * @return SysUserEntity
     */
    public SysUserEntity getCurrentUser() {

        HttpSession session = ContextHolderUtil.getSession();
        SysUserEntity user = (SysUserEntity) session.getAttribute(Constants.SESSION);

        return user;
    }

    /**
     * 获取登录的当前用户的主键
     *
     * @return String
     */
    public String getUserId() {
        return getCurrentUser().getId();
    }

}
